﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Net;
using System.Text.RegularExpressions;

namespace project7
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private async void button1_Click(object sender, EventArgs e)
        {

            // 获取用户输入的关键字
            string keyword = txtkeyword.Text;

            // 使用多个搜索引擎的API进行搜索
            string[] searchUrls = new string[] {
                $"https://www.baidu.com/s?wd={keyword}",
                $"https://www.bing.com/search?q={keyword}"
            };

            // 初始化多个Task对象，并启动多个线程来执行搜索操作
            var tasks = new List<Task<string>>();
            foreach (var url in searchUrls)
            {
                tasks.Add(Task.Factory.StartNew(() =>
                {
                    using (var webClient = new WebClient())
                    {
                        return webClient.DownloadString(url);
                    }
                }));
            }

            // 等待所有搜索操作完成
            await Task.WhenAll(tasks);

            // 从每个搜索结果中提取前200个字符，并更新对应的多行文本框
            for (int i = 0; i < tasks.Count; i++)
            {
                string result = tasks[i].Result;
                int startIndex = result.IndexOf("<body");
                int endIndex = result.IndexOf("</body>");

                if (startIndex != -1 && endIndex != -1)
                {
                    string body = result.Substring(startIndex, endIndex - startIndex);
                    body = Regex.Replace(body, @"<[^>]*>", "").Trim();

                    int bodyLength = Math.Min(body.Length, 200);
                    body = bodyLength < body.Length ? body.Substring(0, bodyLength) : body;

                    if (i == 0)
                    {
                        txtbaiduresult.Text = body;
                    }
                    else if (i == 1)
                    {
                        txtbingresult.Text = body;
                    }
                }
            }
        }
    

        private void keyword_TextChanged(object sender, EventArgs e)
        {

        }

        private void textBox1_TextChanged(object sender, EventArgs e)
        {

        }
    }
}

